var tool = require("./tool"),
    uri = require("url"),
    mail = require("./mail"),
    backHelper = require("./back2PrevHelper"),
    info, buildInfo, deployInfo, username, moduleName;

module.exports = function (next) {
    require("colors");
    require("shelljs/global");

    var argvArr = require("../config.js");
    buildInfo = argvArr[tool.findIn('b', argvArr, 'cmd')]["params"];
    info = require("../build.json/index.json");
    deployInfo = require("../../deploy-conf.json");

    if (exec("cd .build/build.json && git pull").code != 0) {
        console.log("\ngit pull error!".red);
        process.exit(0);
    }

    tool.log("your username: ".green);
    var execInfo = exec("whoami");

    if (execInfo.code != 0) {
        process.exit(0);
    }

    username = execInfo.output.replace("\n", "");
    moduleName = deployInfo.namespaces;

    if (buildInfo.length) {
        var builds = buildInfo[0].split(":");
        if (builds.length == 2) {
            var urls = [], objs = {};
            buildInfo = builds[1].split(",");

            if (builds[0] == "t") {
                objs = findPreviews();
            } else if (builds[0] == "s") {
                objs = findServers();
            }

            urls = objs.serverMap.map(function (item) {
                var parse = uri.parse(item.receiver),
                    href = parse.href.slice(0, parse.href.lastIndexOf("/"));
                return href + "/back2PrevResponse.php";
            });

            startBack(urls, next);
        }
    }

    if (next && next.length) {
        next.shift()(next);
    } else {
        typeof next == "function" && next();
    }
};

function findPreviews() {
    var onlineUrls = findServers(),
        sArr = onlineUrls.serverArr,
        sMap = onlineUrls.serverMap,
        previewUrls = info.previews || [],
        tmp = [], serverArr = [];

    for (var j = 0, length = sArr.length; j < length; j++) {
        var buildItem = sArr[j];
        for (var i = 0, len = previewUrls.length; i < len; i++) {
            if (previewUrls[i].link === buildItem) {
                tmp.push(sMap[i]);
                serverArr.push("preview" + i);
            }
        }
    }

    return {
        serverMap: tmp.concat(),
        serverArr: serverArr
    };
}

function findServers() {
    var serverArr = [], serverMap = [];

    for (var i = 0, len = info.servers.length; i < len; i++) {
        var buildItem = info.servers[i];
        for (var j = 0, length = buildInfo.length; j < length; j++) {
            var item = buildInfo[j];
            if (/^https?:\/\//ig.test(item)) {
                if (buildItem.receiver.indexOf(item) != -1) {
                    serverMap.push(buildItem);
                    serverArr.push("server" + i);
                }
            } else if (/^server(\d)+/ig.test(item) && RegExp["$1"] == i) {
                serverMap.push(buildItem);
                serverArr.push("server" + i);
            } else if (item == buildItem.group) {
                serverMap.push(buildItem);
                serverArr.push("server" + i);
            }
        }
    }

    return {
        serverMap: serverMap,
        serverArr: serverArr
    };
}

function startBack(urls, next) {
    backHelper({
        username: username,
        modulename: moduleName,
        urls: urls
    }, function (backSuccessArr, backFaildArr) {
        mail.sendMail({
            success: backSuccessArr,
            error: backFaildArr
        }, function () {
            if (next && next.length) {
                next.shift()(next);
            } else {
                typeof next == "function" && next();
            }
        }, 1);
    });
}